import { submitAnnualReport } from '@/api/enterpriseQuarterlyReport'
import {
  ENTERPRISE_BASIC_INFORMATION_TABLE_ID,
  ENTERPRISE_BASIC_INFORMATION_TABLE_NAME,
  ENERGY_CONSUMPTION_STRUCTURE_TABLE,
  ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE,
  TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT,
  ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE,
  PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE,
} from '@/config'
import { utils, writeFile } from 'xlsx-js-style'

/* eslint camelcase: off, no-unused-vars: off */
function flattenColumns (columns) {
  const getItems = (arr) => {
    const result = [];
    (function callback (arr) {
      for (let i = 0; i < arr.length; i++) {
        const { children, ...rest } = arr[i]
        if (children && children.length > 0) {
          callback(children)
        } else {
          !rest.hidden && result.push({ ...rest })
        }
      }
    })(arr)
    return result
  }
  return getItems(columns)
}

function withStyle (list) {
  const item = list[0]
  if (!item) return []
  if (!Array.isArray(item)) {
    list = [list]
  }
  return list.map(v => {
    return v.map(vv => ({
      v: vv || '',
      s: {
        border: {
          top: { style: 'thin' },
          right: { style: 'thin' },
          bottom: { style: 'thin' },
          left: { style: 'thin' },
        }
      }
    }))
  })
}

/**
 * 一键导出企业年报
 * @param year{string} 年度
 * @param quarter{string} 季度，年报恒为5
 * @param fileName{string} 导出文件名
 * @returns void
 */
export default async function quickExport (year, quarter, fileName) {
  const { data } = await submitAnnualReport({ year, quarter })
  if (!data) return false

  const value_9 = data[ENTERPRISE_BASIC_INFORMATION_TABLE_ID][0]
  const value_5 = data[ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID]
  const value_8 = data[ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID]
  const value_2 = data[TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.ID]
  const value_1 = data[PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID]
  const value_4 = data[ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.ID]

  function getDesc (value) {
    if (value) {
      return value.reportDescription.replace(/\n\t/g, '\n').split(/\n/)
    }
    return []
  }

  const desc_9 = getDesc(value_9)
  const desc_5 = getDesc(value_5[0])
  const desc_8 = getDesc(value_8[0])
  const desc_2 = getDesc(value_2[0])
  const desc_1 = getDesc(value_1[0])
  const desc_4 = getDesc(value_4[0])

  const appendInformant = v => ([
    [],
    [],
    ['填报负责人：', v.personInCharge, '填报人：', v.informer, '电话：', v.telephone, '填报日期：', v.fillInDate],
  ])

  const appendDescription = (v = []) => ([
    [],
    ...v.map(v => [v])
  ])

  /**
   * @type {{
   *      tenantName: string,
   *      ssdq: string,
   *      ssly: string,
   *      hy: string,
   *      dwlx: string,
   *      dwxxmc: string,
   *      frdwdm: string,
   *      dwzcrq: string,
   *      dwzczb: string,
   *      fddbrxm: string,
   *      lxdh: string,
   *      sfyq: string,
   *      ssyqjtmc: string,
   *      dwdz: string,
   *      yzbm: string,
   *      xzqhdm: string,
   *      dzyx: string,
   *      nygljgmc: string,
   *      cz: string,
   *      zgjnldxm: string,
   *      lxdh1: string,
   *      nyglfzrxm: string,
   *      sj: string,
   *      nyglszh: string,
   *      sftgnygltxrz: string,
   *      tgrq: string,
   *      rzjg: string,
   *      bqgyzcz: string,
   *      sngyzcz: string,
   *      tbgyzcz: string,
   *      bqjgzs: string,
   *      snjgzs: string,
   *      tbjgzs: string,
   *      bqgyzczkbj: string,
   *      sngyzczkbj: string,
   *      tbgyzczkbj: string,
   *      bqxssr: string,
   *      snxssr: string,
   *      tbxssr: string,
   *      bqsjls: string,
   *      snsjls: string,
   *      tbsjls: string,
   *      bqcyry: string,
   *      sncyry: string,
   *      tbcyry: string,
   *      bqnyglsrs: string,
   *      snnyglsrs: string,
   *      tbnyglsrs: string,
   *      bqsccb: string,
   *      snsccb: string,
   *      tbsccb: string,
   *      bqnyxfcb: string,
   *      snnyxfcb: string,
   *      tbnyxfcb: string,
   *      bqnyxfzsccbbl: string,
   *      snnyxfzsccbbl: string,
   *      tbnyxfzsccbbl: string,
   *      bqzhnyxfl: string,
   *      snzhnyxfl: string,
   *      tbzhnyxfl: string,
   *      bqdwzczzhnh: string,
   *      sndwzczzhnh: string,
   *      tbdwzczzhnh: string,
   *      bqzzjrl: string,
   *      snzzjrl: string,
   *      tbzzjrl: string,
   *      bz: string,
   *      year: string,
   *      quarter: string,
   *      fillInDate: string,
   *      informer: string,
   *      personInCharge: string,
   *      telephone: string,
   *      list: string[] | number[]
   * }}
   */
  const v = { ...value_9 }
  const keys = [
    'productName',
    'quantity',
    'unitOfMeasurement',
    'quantityOne',
    'unitOfMeasurementOne',
    'numericalValue',
    'unitOfMeasurementTwo',
  ]
  const header_9 = [
    ['单位名称', v.tenantName, '', '', '年度', '', v.year, ''],
    ['所属地区', v.ssdq, '所属领域', v.ssly, '行业', v.hy, '单位类型', v.dwlx],
    ['单位详细名称', v.dwxxmc, '', '', '法人单位代码', v.frdwdm, '', ''],
    ['单位注册日期', v.dwzcrq, '', '', '单位注册资本（万元）', v.dwzczb, '', ''],
    ['法定代表人姓名', v.fddbrxm, '', '', '联系电话（区号）', v.lxdh, '', ''],
    ['是否央企', v.sfyq, '', '', '所属央企集团名称', v.ssyqjtmc, '', ''],
    ['单位地址', v.dwdz, '', '', '邮政编码', v.yzbm, '', ''],
    ['行政区划代码', v.xzqhdm, '', '', '电子邮箱', v.dzyx, '', ''],
    ['能源管理机构名称', v.nygljgmc, '', '', '传真（区号）', v.cz, '', ''],
    ['主管节能领导姓名', v.zgjnldxm, '', '', '联系电话（区号）', v.lxdh1, '', ''],
    ['能源管理负责人姓名', v.nyglfzrxm, '手机', v.sj, '能源管理师证号', v.nyglszh, '', ''],
    ['是否通过能源管理体系认证', v.sftgnygltxrz, '通过日期', v.tgrq, '认证机构', v.rzjg, '', ''],
    ['指标名称', '', '计量单位', '本期值', '上年值', '同比变化率（%）', '产值及能源消费变化 情况说明 ', ''],
    ['工业总产值', '', '万元', v.bqgyzcz, v.sngyzcz, v.tbgyzcz, v.bz, ''],
    ['价格指数', '', '%', v.bqjgzs, v.snjgzs, v.tbjgzs, '', ''],
    ['工业总产值(可比价)', '', '万元', v.bqgyzczkbj, v.sngyzczkbj, v.tbgyzczkbj, '', ''],
    ['销售收入', '', '万元', v.bqxssr, v.snxssr, v.tbxssr, '', ''],
    ['上缴利税', '', '万元', v.bqsjls, v.snsjls, v.tbsjls, '', ''],
    ['从业人员', '', '人', v.bqcyry, v.sncyry, v.tbcyry, '', ''],
    ['能源管理师人数', '', '人', v.bqnyglsrs, v.snnyglsrs, v.tbnyglsrs, '', ''],
    ['生产成本', '', '万元', v.bqsccb, v.snsccb, v.tbsccb, '', ''],
    ['能源消费成本', '', '万元', v.bqnyxfcb, v.snnyxfcb, v.tbnyxfcb, '', ''],
    ['能源消费占生产成本比例', '', '%', v.bqnyxfzsccbbl, v.snnyxfzsccbbl, v.tbnyxfzsccbbl, '', ''],
    ['综合能源消费量(当量值)', '', '万吨标准煤', v.bqzhnyxfl, v.snzhnyxfl, v.tbzhnyxfl, '', ''],
    ['单位总产值综合能耗(当量值)', '', '吨标准煤/万元', v.bqdwzczzhnh, v.sndwzczzhnh, v.tbdwzczzhnh, '', ''],
    ['主要产品名称', '', '年产能', '', '年产量', '', '单位产品能耗', ''],
    ['', '', '数量', '计量单位', '数量', '计量单位', '数值', '计量单位'],
    ...(v.list || []).map(vv => {
      const item = keys.map(key => vv[key])
      item.splice(1, 0, '')
      return item
    })
  ]

  const header_5 = flattenColumns(ENERGY_CONSUMPTION_STRUCTURE_TABLE.COLUMNS)
  const header_8 = flattenColumns(ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.COLUMNS)
  const header_2 = flattenColumns(TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.COLUMNS)
  const header_1 = flattenColumns(PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.COLUMNS)
  const header_4 = flattenColumns(ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.COLUMNS)

  const aoa_9 = [
    ...withStyle(header_9),
    ...appendInformant(value_9 || {}),
    ...appendDescription(desc_9)
  ]
  const aoa_5 = [
    ...withStyle(header_5.map(v => v.label)),
    ...withStyle(value_5.map(v => header_5.map(vv => vv.prop).map(prop => v[prop]))),
    ...appendInformant(value_5[0] || {}),
    ...appendDescription(desc_5)
  ]
  const aoa_8 = [
    ...withStyle(header_8.map(v => v.label)),
    ...withStyle(value_8.map(v => header_8.map(vv => vv.prop).map(prop => v[prop]))),
    ...appendInformant(value_8[0] || {}),
    ...appendDescription(desc_8)
  ]
  const aoa_2 = [
    ...withStyle(header_2.map(v => v.label)),
    ...withStyle(value_2.map(v => header_2.map(vv => vv.prop).map(prop => v[prop]))),
    ...appendInformant(value_2[0] || {}),
    ...appendDescription(desc_2)
  ]
  const aoa_1 = [
    ...withStyle(header_1.map(v => v.label)),
    ...withStyle(value_1.map(v => header_1.map(vv => vv.prop).map(prop => v[prop]))),
    ...appendInformant(value_1[0] || {}),
    ...appendDescription(desc_1)
  ]
  const aoa_4 = [
    ...withStyle(header_4.map(v => v.label)),
    ...withStyle(value_4.map(v => header_4.map(vv => vv.prop).map(prop => v[prop]))),
    ...appendInformant(value_4[0] || {}),
    ...appendDescription(desc_4)
  ]

  const sheet_9_name = ENTERPRISE_BASIC_INFORMATION_TABLE_NAME
  const sheet_5_name = ENERGY_CONSUMPTION_STRUCTURE_TABLE.NAME
  const sheet_8_name = ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.NAME
  const sheet_2_name = TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.NAME
  const sheet_1_name = PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.NAME
  const sheet_4_name = ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.NAME

  const ws_9 = utils.aoa_to_sheet(aoa_9)
  const ws_5 = utils.aoa_to_sheet(aoa_5)
  const ws_8 = utils.aoa_to_sheet(aoa_8)
  const ws_2 = utils.aoa_to_sheet(aoa_2)
  const ws_1 = utils.aoa_to_sheet(aoa_1)
  const ws_4 = utils.aoa_to_sheet(aoa_4)

  ws_9['!merges'] = [
    { s: { r: 0, c: 1 }, e: { r: 0, c: 3 } }, { s: { r: 0, c: 5 }, e: { r: 0, c: 7 } },
    { s: { r: 2, c: 1 }, e: { r: 2, c: 3 } }, { s: { r: 2, c: 5 }, e: { r: 2, c: 7 } },
    { s: { r: 3, c: 1 }, e: { r: 3, c: 3 } }, { s: { r: 3, c: 5 }, e: { r: 3, c: 7 } },
    { s: { r: 4, c: 1 }, e: { r: 4, c: 3 } }, { s: { r: 4, c: 5 }, e: { r: 4, c: 7 } },
    { s: { r: 5, c: 1 }, e: { r: 5, c: 3 } }, { s: { r: 5, c: 5 }, e: { r: 5, c: 7 } },
    { s: { r: 6, c: 1 }, e: { r: 6, c: 3 } }, { s: { r: 6, c: 5 }, e: { r: 6, c: 7 } },
    { s: { r: 7, c: 1 }, e: { r: 7, c: 3 } }, { s: { r: 7, c: 5 }, e: { r: 7, c: 7 } },
    { s: { r: 8, c: 1 }, e: { r: 8, c: 3 } }, { s: { r: 8, c: 5 }, e: { r: 8, c: 7 } },
    { s: { r: 9, c: 1 }, e: { r: 9, c: 3 } }, { s: { r: 9, c: 5 }, e: { r: 9, c: 7 } },

    { s: { r: 10, c: 4 }, e: { r: 10, c: 5 } }, { s: { r: 10, c: 6 }, e: { r: 10, c: 7 } },
    { s: { r: 11, c: 4 }, e: { r: 11, c: 5 } }, { s: { r: 11, c: 6 }, e: { r: 11, c: 7 } },
    { s: { r: 12, c: 0 }, e: { r: 12, c: 1 } }, { s: { r: 12, c: 4 }, e: { r: 12, c: 5 } }, { s: { r: 12, c: 6 }, e: { r: 12, c: 7 } },
    { s: { r: 13, c: 0 }, e: { r: 13, c: 1 } }, { s: { r: 13, c: 4 }, e: { r: 13, c: 5 } }, { s: { r: 13, c: 6 }, e: { r: 24, c: 7 } },
    { s: { r: 14, c: 0 }, e: { r: 14, c: 1 } }, { s: { r: 14, c: 4 }, e: { r: 14, c: 5 } },
    { s: { r: 15, c: 0 }, e: { r: 15, c: 1 } }, { s: { r: 15, c: 4 }, e: { r: 15, c: 5 } },
    { s: { r: 16, c: 0 }, e: { r: 16, c: 1 } }, { s: { r: 16, c: 4 }, e: { r: 16, c: 5 } },
    { s: { r: 17, c: 0 }, e: { r: 17, c: 1 } }, { s: { r: 17, c: 4 }, e: { r: 17, c: 5 } },
    { s: { r: 18, c: 0 }, e: { r: 18, c: 1 } }, { s: { r: 18, c: 4 }, e: { r: 18, c: 5 } },
    { s: { r: 19, c: 0 }, e: { r: 19, c: 1 } }, { s: { r: 19, c: 4 }, e: { r: 19, c: 5 } },
    { s: { r: 20, c: 0 }, e: { r: 20, c: 1 } }, { s: { r: 20, c: 4 }, e: { r: 20, c: 5 } },
    { s: { r: 21, c: 0 }, e: { r: 21, c: 1 } }, { s: { r: 21, c: 4 }, e: { r: 21, c: 5 } },
    { s: { r: 22, c: 0 }, e: { r: 22, c: 1 } }, { s: { r: 22, c: 4 }, e: { r: 22, c: 5 } },
    { s: { r: 23, c: 0 }, e: { r: 23, c: 1 } }, { s: { r: 23, c: 4 }, e: { r: 23, c: 5 } },
    { s: { r: 24, c: 0 }, e: { r: 24, c: 1 } }, { s: { r: 24, c: 4 }, e: { r: 24, c: 5 } },
    { s: { r: 25, c: 0 }, e: { r: 26, c: 1 } }, { s: { r: 25, c: 2 }, e: { r: 25, c: 3 } }, { s: { r: 25, c: 4 }, e: { r: 25, c: 5 } }, { s: { r: 25, c: 6 }, e: { r: 25, c: 7 } },
    { s: { r: 26, c: 7 }, e: { r: 26, c: 7 } },
    { s: { c: 0 }, e: { c: 1 } }, { s: { c: 7 }, e: { c: 7 } },
  ]

  const wb = utils.book_new();
  const sheets = [
    { ws: ws_9, name: sheet_9_name },
    { ws: ws_5, name: sheet_5_name },
    { ws: ws_8, name: sheet_8_name },
    { ws: ws_2, name: sheet_2_name },
    { ws: ws_1, name: sheet_1_name },
    { ws: ws_4, name: sheet_4_name },
  ]
  sheets.forEach(v => {
    utils.book_append_sheet(wb, v.ws, v.name)
  })

  writeFile(wb, fileName + '.xlsx')
}
